package com.yango.smsservice.controller;

import com.yango.commonutil.result.Result;
import com.yango.commonutil.utils.RandomUtil;
import com.yango.smsservice.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Li.Ding.yin
 * @create 2021年07月30日19:57-星期五
 * @role 短信服务控制层
 */
@Api(description = "短信服务控制层")
@RestController
@RequestMapping("/api/sms")
public class SmsController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //根据手机号发送短信验证码
    @ApiOperation(value = "根据手机号发送短信验证码")
    @GetMapping("/sendCode/{phone}")
    public Result sendCode(@ApiParam(name = "phone", value = "手机号", required = true)
                           @PathVariable String phone) {

        //查询redis是否有短信验证码
        String code = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(code)) {
            return Result.ok().message("验证码发送成功!");
        }
        //模拟验证码发送成功
        code = "1234";
        //将验证码放到redis中并设置有效时间为5分钟
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        return Result.ok().message("验证码发送成功!");
        //没有获取到，发送验证码
        //使用工具类生成四位数字的验证码
        //code = RandomUtil.getFourBitRandom();
        //将验证码放到map集合中
//        Map<String, Object> param = new HashMap<>();
//        param.put("code", code);
        //调用业务层方法发送短信
//        boolean isSend = smsService.sendCode(phone, "SMS_180051135", param);
//        if (isSend) {
        //将验证码放到redis中并设置有效时间为5分钟
        //redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
//            return Result.ok().message("验证码发送成功!");
//        } else {
//            return Result.error().message("验证码发送失败!");
//        }
    }
}
